
var http = require('http');  
var fs = require('fs');
var UUID = require('node-uuid');
var unzip = require('unzip');
// http.createServer(function (req, res) {  
  
//     var uid = UUID.v1();
//     var zippath = "../storage/zip/"+uid+".zip";
//    	req.pipe(fs.createWriteStream(zippath));
   
//     // 发送 HTTP 头部   
//     // HTTP 状态值: 200 : OK  
//     // 内容类型: text/plain  
//     res.writeHead(200, {'Content-Type': 'text/plain'});  
  	
//     // 发送响应数据 "Hello World"  
//     res.end('Hello World\n');  
// }).listen(8888);  

var express = require('express');
var app = express();
var path = require('path');
var zlib = require('zlib');
var packmiddle = require('./wxpack_middle.js');

app.use(function (req, res, next) {
	if (req.query.token !== 'we7xx256') {
		res.status(403).end();
		return;
	}
	next();
});

app.post('/wxpack', packmiddle, function (req, res, next) {
	// 下载文件
	var basename = path.basename(req.file.filename,'.zip');
	var filePath = path.join(__dirname, '../storage/wx/'+basename+'.wx'); 
	var stats = fs.statSync(filePath);
	console.log('filesize:'+stats.size);  
	if (stats.isFile()){ 
		res.set({ 
			'Content-Type': 'application/octet-stream', 
			'Content-Disposition': 'attachment; filename='+basename, 
			'Content-Length': stats.size 
		}); 
		var gzipStream = zlib.createGzip(); //gzip 压缩
		fs.createReadStream(filePath).pipe(res).on('finish',function(){
			res.status(200).end();
		});
	} else { 
		res.status(404).end();
	} 
});

http.createServer(app).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');